console.log("loading vectrite.js");
Vectrite.Vrite = Vectrite.Class();
Vectrite.Vrite.prototype = {
   flag: 0,
   initialize: function(animations, tweens, state, x, y) {
      this.animations = animations;
      this.state = state;
      this.tweens = tweens;
      this.frame = 0;
      this.prevFrame;
      this.context = Vectrite.inst.context;
      this.x = x;
      this.y = y;
   },
   next: function() { this.frame = (this.frame + 1 < this.animations[this.state].length) ? this.frame + 1 : 0 },
   draw: function() {
      var fr = this.animations[this.state][this.frame];
      if (this.tweenDuration > 0) {
         this.tween();
      }
      else {
         this.drawFrame(fr);
         this.next();
      }
   },
   tween: function() {
      this.tweens[this.currentTween](this.prevFrame);
      this.tweenDuration--;
      this.drawFrame(this.prevFrame);
   },
   drawFrame: function(fr) {
      var x = this.x; var y = this.y;
      var storePrev = 0;
      for (i in fr) {
         var cmd = fr[i];
         /* initiate tweening */
         if (cmd.c == 'x') {
            this.currentTween = cmd.x;
            this.tweenDuration = cmd.d;
            this.tween();
         }
         /* style */
         else if (cmd.c == 's') {
            //console.log("style: " + cmd.s);
            for (s in cmd.s)
               Vectrite.inst.styles[cmd.s[s]](this.context);
         }
         /* draw command */
         else {
            storePrev = 1;
            this.exec(cmd, x, y);
         }
      }
      if (storePrev)
         this.prevFrame = Vectrite.copy(fr);
   },
   exec: function(cmd, x, y) {
      if (!this.cmdhandlers[cmd.c]) {
         console.log("Unknown cmd: " + cmd.c);
      }
      else {
         //console.log(this.cmdhandlers[cmd.c] + "\n" + cmd.p);
         Vectrite.bind(this, this.cmdhandlers[cmd.c])(cmd, x, y);
      }
   },

   cmdhandlers: {
      'b': function(cmd, x, y) { this.context.beginPath(); },
      'm': function(cmd, x, y) { this.context.moveTo(); },
      'c': function(cmd, x, y) { this.context.closePath(); },
      'l': function(cmd, x, y) { this.context.lineTo(cmd.p[0] + x, cmd.p[1] + y); },
      'q': function(cmd, x, y) { this.context.quadraticCurveTo(cmd.p[0] + x, cmd.p[1] + y, cmd.p[2] + x, cmd.p[3] + y); },
      'z': function(cmd, x, y) { this.context.bezierCurveTo(cmd.p[0] + x, cmd.p[1] + y, cmd.p[2] + x, cmd.p[3] + y, cmd.p[4] + x, cmd.p[5] + y); },
      'a': function(cmd, x, y) { this.context.arcTo(cmd.p[0] + x, cmd.p[1] + y, cmd.p[2] + x, cmd.p[2]+ y, cmd.p[3]); },
      'd': function(cmd, x, y) { this.context.arc(cmd.p[0] + x, cmd.p[1] + y, cmd.p[2], cmd.p[3], cmd.p[4]); },
      'e': function(cmd, x, y) { this.context.rect(cmd.p[0] + x, cmd.p[1] + y, cmd.p[2], cmd.p[3]); },
      't': function(cmd, x, y) { this.context.stroke(); },
      'f': function(cmd, x, y) { this.context.fill(); }
   }
}
console.log("loaded vectrite.js");